// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:flutter/material.dart';
import 'package:kkhousekeep/tools/log.dart';

typedef TabControllerListener = void Function(TabController controller);

typedef TabControllerBuilder = Widget Function(TabController controller);

class KKDefaultTabController extends StatefulWidget {
  const KKDefaultTabController({
    super.key,
    required this.length,
    required this.builder,
    this.onTabListener,
    this.initialIndex = 0,
    this.animationDuration,
  })  : assert(length >= 0),
        assert(length == 0 || (initialIndex >= 0 && initialIndex < length));

  final int length;

  final int initialIndex;

  final Duration? animationDuration;

  final TabControllerBuilder builder;

  final TabControllerListener? onTabListener;

  @override
  State<KKDefaultTabController> createState() => _KKDefaultTabControllerState();
}

class _KKDefaultTabControllerState extends State<KKDefaultTabController>
    with SingleTickerProviderStateMixin {
  late TabController _controller;

  @override
  void initState() {
    super.initState();
    _controller = TabController(
      vsync: this,
      length: widget.length,
      initialIndex: widget.initialIndex,
      animationDuration: widget.animationDuration,
    );
    _controller.addListener(onScroller);
  }

  void onScroller(){
    widget.onTabListener?.call(_controller);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(_controller);
  }
}
